﻿using MiniCAP.Core;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace MiniCAP.MySQL
{
    public class MySqlMessageStorage : IMessageStorage
    {
        private readonly string _connectionString;

        public MySqlMessageStorage(string connectionString)
        {
            _connectionString = connectionString;
        }

        public async Task<string> StoreMessageAsync(string topic, object content, IDbTransaction? transaction = null)
        {
            var messageId = Guid.NewGuid().ToString();
            var sql = @"  
            INSERT INTO mini_cap_published (MessageId, Topic, Content, Status, CreatedAt, UpdatedAt)  
            VALUES (@MessageId, @Topic, @Content, @Status, @CreatedAt, @UpdatedAt)";

            var parameters = new
            {
                MessageId = messageId,
                Topic = topic,
                Content = JsonSerializer.Serialize(content),
                Status = MessageStatus.Scheduled.ToString(),
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            if (transaction != null)
            {
                await transaction.Connection.ExecuteAsync(sql, parameters, transaction);
            }
            else
            {
                using var connection = new MySqlConnection(_connectionString);
                await connection.ExecuteAsync(sql, parameters);
            }

            return messageId;
        }

        // 其他方法实现...  
    }
}
